<html>
    <head>
        <meta charset="UTF-8">
        <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.0/socket.io.js"></script>
    </head>
    <body>
        <ul id = "msgs"> </ul>

        <ul id="messages"></ul>
        <input id=" nickname" placeholder="请输入名称"/>
        <input id=" msg" placeholder="请输入消息"/>
        <button onclick="sendMsg()">发送</button>
    </body>

    <script>

        var socket = io()
        function sendMsg(){
            var nickname = document.getElementById(" nickname").value
            var msg = document.getElementById(" msg").value

            msg= nickname+":"+msg +(new Date().toLocaleTimeString());

            //发送
            socket.send(msg);
            createElement(msg);
        }

        socket.on("message",function (message){
            createElement(message);
        })

        function createElement(msg){
            var li = document.createElement('li');
            li.textContent = msg;
            document.getElementById("messages").appendChild(li)
        }
    </script>
</html>